/**
 * Copyright 2011 Joe Choi, All rights reserved.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0

 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package tec.data.persistence.jdbc;

import tao.data.persistence.Record;
import tec.data.persistence.RecordBuffer;
import tec.data.structure.ListControl;

/**
 * @author Joe Choi
 */
public class JDBCRecordBuffer implements RecordBuffer {
	public JDBCRecordBuffer(ResultSetAdapter source) {
		this(source, INIT_FETCH_SIZE);
	}
	
	public JDBCRecordBuffer(ResultSetAdapter source, long initFetchSize) {
		if(source == null || initFetchSize <= 0)
			throw new IllegalArgumentException();
		this.source = source;
		this.fetchSize = 500;
		this.buffer = new ListControl<Record>();
		load(initFetchSize);
	}
	
	@Override
	public void first() {
		index = 0;
	}

	@Override
	public void last() {
		index = buffer.getList().size() - 1;
	}

	@Override
	public boolean hasNext() {
		if(index < 0) {
			index = 0;
			return(true);
		}
		// index is greater than 0
		if(index < buffer.getList().size()) return(true);
		
		//try to load more records
		load(this.fetchSize);
		return(index >= 0 && index < buffer.getList().size());
	}

	@Override
	public Record next() {
		return(buffer.getList().get(index++));
	}

	@Override
	public boolean hasPrevious() {
		return(index >= 0 && index < buffer.getList().size());
	}

	@Override
	public Record previous() {
		return(buffer.getList().get(index--));
	}

	@Override
	public int size() {
		return(buffer.getList().size());
	}

	@Override
	public void setFetchSize(int size) {
		this.fetchSize = size;
	}

	@Override
	public int getFetchSize() {
		return(this.fetchSize);
	}

	private void load(long size) {
		int loadCount = 0;
		while(source.next()) {
			buffer.add(source.getRecord());
			loadCount++;
			if(loadCount >= size) return;
		}
	}
	
	private final static long INIT_FETCH_SIZE = 500;
	private int index;
	private int fetchSize;
	private ListControl<Record> buffer;
	private ResultSetAdapter source;
}
